package com.hkw.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid数据库连接池工具类
 */
public class DruidUtils {
    public static DataSource dataSource;
    //初始化datasource
    static {
        Properties p = new Properties();
        InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("resources/druid.properties");
        try {
            p.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    //返回datasource
    public static DataSource getDataSource(){
        return dataSource;
    }
    //返回Connection
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //关闭连接
    public static void close(Connection con , Statement state){
        try {
            if(con != null && state != null) {
                state.close();
                con.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭连接
    public static void close(Connection con , Statement state , ResultSet rs){
        try {
            if(rs!=null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        close(con,state);
    }
}
